package com.springboot.sql.service.impl;

import com.springboot.sql.dao.TSysMenuDao;
import com.springboot.sql.dao.entity.SysMenu;
import com.springboot.sql.service.IMenuService;
import com.springboot.vo.res.Menu;
import com.springboot.vo.res.ZTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * On 2017/2/24 0024.
 */
@Service
public class MenuServiceImpl implements IMenuService{

    private final TSysMenuDao tSysMenuDao;


    @Autowired
    public MenuServiceImpl(TSysMenuDao tSysMenuDao) {
        this.tSysMenuDao = tSysMenuDao;
    }

    @Override
    public List<Menu> getMenuByRoles(List<String> roles) {
        List<SysMenu> sysMenus;
        sysMenus=tSysMenuDao.findMenuByRoles(roles);
        //取出的菜单是按照menu_id排序的，以下为组装菜单
        Map<String,Menu> menuMap= new HashMap<>();
        List<Menu> menus = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            Menu menu = new Menu();
            menu.setChild(new ArrayList<>());
            menu.setMenuName(sysMenu.getMenuName());
            menu.setHttpAddress(sysMenu.getHttpAddress());
            menuMap.put(sysMenu.getMenuId(), menu);
            if (sysMenu.getMenuPid().equals("")) {
                menus.add(menu);
            } else {
//                VerityDoUtils.isNotNullDo(menuMap.get(sysMenu.getMenuPid()),(parent)->{
//                    parent.getChild().add(menu);
//                });
                Menu parent = menuMap.get(sysMenu.getMenuPid());
                if (parent != null)
                    parent.getChild().add(menu);
            }
        }
        return menus;
    }

    @Override
    public List<ZTree> getAllPermission4ZTree(String roleId) {
        return tSysMenuDao.findByRoleIsHaveMenuList(roleId).stream().map(m->{
            ZTree zTree = new ZTree();
            zTree.setId(m.getMenuId());
            zTree.setName(m.getMenuName());
            zTree.setpId(m.getMenuPid());
            zTree.setChecked(m.getHave());
            return zTree;
        }).collect(Collectors.toList());
    }

}
